<template>
	<div class="head-image-box" :style="{ width: size + 'px', height: size + 'px' }" @click="onClick">
		<img v-if="url" class="avatar-image" :src="url" :style="avatarStyle" loading="lazy" />
		<div v-else class="avatar-text" :style="avatarStyle">
			{{ name?.substring(0, 2).toUpperCase() }}
		</div>
		<div v-if="userType === 'ROBOT'" class="user-type-tag">机器人</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			colors: ["#5daa31", "#c7515a", "#e03697", "#85029b", "#c9b455", "#326eb6"]
		}
	},
	props: {
		url: String,
		name: String,
		size: {
			type: Number,
			default: 40
		},
		id: Number,
		isShowUserInfo: {
			type: Boolean,
			default: true
		},
		isQueryUser: {
			type: Boolean,
			default: true
		},
		userType: {
			type: String,
			default: 'USER'
		},
		isSelf: {
			type: Boolean,
			default: false
		}
	},
	methods: {
		onClick(event) {
			if (this.isSelf) {
				this.$store.commit('uiStore/showUserSetting', true);
				return;
			}
			
			if (!this.isShowUserInfo) return;
			
			if (!this.isQueryUser) {
				this.$emit('click');
				return;
			}
			
			const url = this.userType === 'ROBOT' 
				? `/robot/find/${this.id}`
				: `/user/find/${this.id}`;
				
			this.$http({
				url: url,
				method: 'get'
			}).then((info) => {
				console.log(info);
				info.memberType = info.memberType || this.userType;
				info.pos = {
					x: event.clientX,
					y: event.clientY
				};
				this.$store.commit("uiStore/showUserInfoBox", info);
			}).catch((error) => {
				this.$message.error('获取用户信息失败');
			});
		}
	},
	computed: {
		avatarStyle() {
			return {
				width: this.size + 'px',
				height: this.size + 'px',
				borderRadius: '4px',
				backgroundColor: this.name ? this.textColor : '#fff',
				fontSize: this.size * 0.35 + 'px',
				lineHeight: this.size + 'px'
			}
		},
		textColor() {
			if (!this.name) return this.colors[0];
			let hash = 0;
			for (let i = 0; i < this.name.length; i++) {
				hash += this.name.charCodeAt(i);
			}
			return this.colors[hash % this.colors.length];
		}
	}
}
</script>

<style lang="scss">
.head-image-box {
	position: relative;
	border-radius: 4px;
	overflow: hidden;
	cursor: pointer;
	
	.avatar-image {
		display: block;
		object-fit: cover;
	}

	.avatar-text {
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		text-align: center;
	}

	.user-type-tag {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background: rgba(0, 0, 0, 0.5);
		color: white;
		font-size: 10px;
		text-align: center;
		padding: 1px 0;
	}
}
</style>